<template>
  <div class="add-order">
    <h2>添加订单</h2>
    <el-button @click="goBack">返回订单列表</el-button>
    <!-- 新增下载导入模板按钮 -->
    <el-button @click="downloadTemplate">下载导入模板</el-button>
    <el-upload
      action="#"
      :show-file-list="false"
      :on-change="handleFileChange"
      :before-upload="beforeUpload"
      accept=".csv"
    >
      <el-button type="primary">导入订单</el-button>
    </el-upload>
    <el-form :model="order" label-width="120px">
      <el-form-item label="订单管理员">
        <el-input v-model="this.$route.params.order_admin":disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="订单名称">
        <el-input v-model="order.order_name"></el-input>
      </el-form-item>
      <el-form-item label="订单ID">
        <el-input v-model="this.newOrderId":disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="订单价格">
        <el-input v-model="order.order_price" type="number" readonly></el-input>
      </el-form-item>
      <el-form-item label="订单状态">
        <el-select v-model="order.order_status">
          <el-option label="未付款" :value="7"></el-option>
          <el-option label="支付待审核" :value="1"></el-option>
          <el-option label="待发货" :value="2"></el-option>
          <el-option label="已发货" :value="3"></el-option>
          <el-option label="已签收" :value="4"></el-option>
          <el-option label="退货审核" :value="5"></el-option>
          <el-option label="已退货" :value="6"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="联系电话">
        <el-input v-model="order.order_phone"></el-input>
      </el-form-item>
      <el-form-item label="收货地址">
        <el-input v-model="order.order_address"></el-input>
      </el-form-item>
      <el-form-item label="省份">
        <el-select v-model="order.order_province" placeholder="请选择省份">
          <el-option v-for="province in provinces" :key="province" :label="province" :value="province"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="order.order_remark" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="商品列表">
        <!-- 商品选择对话框 -->
        <el-button type="primary" @click="showGoodsDialog = true">选择商品</el-button>
        <el-dialog v-model="showGoodsDialog" title="选择商品" width="70%">
      <!-- 搜索框 -->
      <el-input
        v-model="searchQuery"
        placeholder="请输入商品名称或ID进行搜索"
        style="margin-bottom: 20px;"
        @input="handleSearch"
      ></el-input>

      <!-- 使用原生表格展示商品列表 -->
      <table class="custom-table">
        <thead>
          <tr>
            <th style="width: 55px;"></th>
            <th>商品ID</th>
            <th>商品名称</th>
            <th>价格</th>
            <th>库存</th>
            <th>商品描述</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="goods in paginatedCommodities" :key="goods.commodity_id">
            <td>
              <input
                type="checkbox"
                :checked="selectedGoods.some(item => item.commodity_id === goods.commodity_id)"
                @change="toggleGoodsSelection(goods)"
              >
            </td>
            <td>{{ goods.commodity_id }}</td>
            <td>{{ goods.commodity_name }}</td>
            <td>{{ goods.commodity_price }}</td>
            <td>{{ goods.commodity_inventory }}</td>
            <td>{{ goods.commodity_desc }}</td>
          </tr>
        </tbody>
      </table>

      <!-- 分页组件 -->
      <el-pagination
        style="margin-top: 20px; text-align: right;"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="filteredCommodities.length"
        @current-change="handlePageChange"
        layout="prev, pager, next"
      ></el-pagination>

      <template #footer>
        <el-button @click="showGoodsDialog = false">取消</el-button>
        <el-button type="primary" @click="addSelectedGoods">确认添加</el-button>
      </template>
    </el-dialog>
        <!-- 已选商品列表 -->
        <table class="custom-table">
          <thead>
            <tr>
              <th>商品ID</th>
              <th>商品名称</th>
              <th>商品描述</th>
              <th>数量</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(goods, index) in order.order_goodslist" :key="goods.goods_id">
              <td>{{ goods.goods_id }}</td>
              <td>{{ goods.goods_name+goods.goods_desc }}</td>
              <td>{{ goods.goods_desc }}</td>
              <td>
                <el-input
                  v-model.number="goods.goods_num"
                  type="number"
                  min="1"
                  style="width: 120px"
                  @input="validateGoodsQuantity(goods)"
                ></el-input>
              </td>
              <td>
                <el-button
                  type="danger"
                  size="small"
                  @click="removeGoods(index)"
                >删除</el-button>
              </td>
            </tr>
          </tbody>
        </table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitOrder">提交</el-button>
        <el-button @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      showGoodsDialog: false,
      selectedGoods: [], // 临时存储选中的商品
      commodities: [], // 从接口获取的商品列表
      searchQuery: '', // 搜索关键词
      filteredCommodities: [], // 过滤后的商品列表
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示的商品数量
      newOrderId: '',
      order: {
        order_admin: '',
        order_name: '',
        order_id: '',
        order_price: 0,
        order_status: 7,
        order_phone: '',
        order_address: '',
        order_province: '',
        order_remark: '',
        order_goodslist: [] // 商品列表
      },
      provinces: [
        '北京',
        '上海',
        '广东',
        '广西',
        '江苏',
        '浙江',
        '四川',
        '湖北',
        '河北',
        '河南',
        '云南',
        '辽宁',
        '黑龙江',
        '湖南',
        '安徽',
        '山东',
        '新疆',
        '甘肃',
        '山西',
        '内蒙古',
        '陕西',
        '吉林',
        '江西',
        '贵州',
        '海南',
        '宁夏',
        '青海',
        '西藏',
        '重庆',
        '天津'
      ]
    };
  },
  computed: {
    // 分页后的商品列表
    paginatedCommodities() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredCommodities.slice(start, end);
    }
  },
  created() {
    this.fetchCommodities();
    this.generateAndAssignOrderId();
    
  },
  methods: {


     generateOrderId() {
    // 获取当前时间戳
    const timestamp = new Date().getTime();
    // 生成一个 0 到 999 之间的随机数
    const randomNum = Math.floor(Math.random() * 1000);
    // 将时间戳和随机数拼接成订单 ID
    const orderid=`${timestamp}${randomNum}`
    return orderid;
},
generateAndAssignOrderId() {
      // 调用生成订单 ID 的方法
      const Id = this.generateOrderId();
      // 将生成的订单 ID 赋值给 order.order_id
      this.newOrderId = Id;
      this.order.order_id=this.newOrderId;
    
  },
    // 添加商品

    addGoods() {
      this.order.order_goodslist.push({
        goods_id: '',
        goods_name: '',
        goods_desc: '',
        goods_num: 1
      });
      this.calculateOrderPrice();
    },
    async fetchCommodities() {
      try {
        const res = await axios.get('http://127.0.0.1:3005/order/getcommodity');
        if (res.data && res.data.res && res.data.res.result) {
          this.commodities = res.data.res.result;
          this.filteredCommodities = this.commodities; // 初始化过滤后的商品列表
        } else {
          this.$message.error('获取商品列表数据格式错误');
        }
      } catch (error) {
        this.$message.error('获取商品列表失败');
        console.error(error);
      }
    },
    // 处理商品选择
    toggleGoodsSelection(goods) {
      const index = this.selectedGoods.findIndex(item => item.commodity_id === goods.commodity_id);
      if (index > -1) {
        this.selectedGoods.splice(index, 1);
      } else {
        this.selectedGoods.push(goods);
      }
    },
    // 添加选中的商品
    addSelectedGoods() {
      this.selectedGoods.forEach(goods => {
        // 检查是否已存在
        const exists = this.order.order_goodslist.some(
          item => item.goods_id === goods.commodity_id
        );
        if (!exists) {
          this.order.order_goodslist.push({
            goods_id: goods.commodity_id,
            goods_name: goods.commodity_name,
            goods_desc: goods.commodity_desc,
            goods_num: 1
          });
        }
      });
      this.showGoodsDialog = false;
      this.$message.success('添加商品成功');
      this.calculateOrderPrice();
    },

    handleSearch() {
      this.filteredCommodities = this.commodities.filter(goods => {
        return (
          goods.commodity_name.includes(this.searchQuery) ||
          goods.commodity_id.toString().includes(this.searchQuery)
        );
      });
      this.currentPage = 1; // 重置到第一页
    },
    // 处理分页变化
    handlePageChange(page) {
      this.currentPage = page;
    },
    // 删除商品
    removeGoods(index) {
      this.order.order_goodslist.splice(index, 1);
      this.calculateOrderPrice();
    },
    // 提交订单
    submitOrder() {
      // 验证商品列表
      if (this.order.order_goodslist.length === 0) {
        this.$message.warning('请至少添加一个商品');
        return;
      }
      const requiredFields = [
        'order_admin',
        'order_name',
        'order_id',
        'order_price',
        'order_status',
        'order_phone',
        'order_address',
        'order_province'
      ];
      this.order.order_admin=this.$route.params.order_admin
      for (const field of requiredFields) {
        if (!this.order[field]) {
          this.$message.warning(`请填写 ${field}`);
          return;
        }
      }
      // 验证手机号码格式
      const phoneRegex = /^1[3-9]\d{9}$/;
      if (!phoneRegex.test(this.order.order_phone)) {
        this.$message.warning('请输入有效的手机号码');
        return;
      }
      // 验证商品数量是否超过库存
      for (const goods of this.order.order_goodslist) {
        const commodity = this.commodities.find(item => item.commodity_id === goods.goods_id);
        if (commodity && goods.goods_num > commodity.commodity_inventory) {
          this.$message.warning(`商品 ${goods.goods_name} 的数量不能超过库存 ${commodity.commodity_inventory}`);
          return;
        }
      }
      this.order.order_goodslist.forEach(goods => {
        goods.goods_name = `${goods.goods_name} ${goods.goods_desc}`;
      });
      // 转换字段类型
      this.order.order_price = Number(this.order.order_price);
      this.order.order_status = Number(this.order.order_status);
      this.order.order_phone = Number(this.order.order_phone);

      // 确保商品列表是数组
      if (!this.order.order_goodslist || !Array.isArray(this.order.order_goodslist)) {
        this.order.order_goodslist = [];
      }
      // 提交订单
      axios.post('http://127.0.0.1:3005/order/createOrder', this.order)
        .then(() => {
          this.$message.success('订单添加成功');
          this.$router.push(`/orderList/${this.order.order_admin}`);
        })
        .catch(error => {
          console.error(error);
          this.$message.error('订单添加失败' + error.message);
        });
    },
    // 返回订单列表
    goBack() {
      this.$router.go(-1);    },
    // 处理文件上传前的检查
    beforeUpload(file) {
      const isCSV = file.type === 'text/csv';
      if (!isCSV) {
        this.$message.error('请上传 CSV 文件');
      }
      return isCSV;
    },
    // 处理文件上传
    handleFileChange(file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          const csvData = e.target.result;
          const lines = csvData.split('\n');
          const headers = lines[0].split(',');
          // 解析订单信息
          const orderInfo = lines[1].split(',');
          this.order.order_admin = orderInfo[headers.indexOf('order_admin')];
          this.order.order_name = orderInfo[headers.indexOf('order_name')];
          this.order.order_id = orderInfo[headers.indexOf('order_id')];
          this.order.order_price = Number(orderInfo[headers.indexOf('order_price')]);
          this.order.order_status = Number(orderInfo[headers.indexOf('order_status')]);
          this.order.order_phone = orderInfo[headers.indexOf('order_phone')];
          this.order.order_address = orderInfo[headers.indexOf('order_address')];
          this.order.order_province = orderInfo[headers.indexOf('order_province')];
          this.order.order_remark = orderInfo[headers.indexOf('order_remark')];
          // 解析商品列表
          this.order.order_goodslist = [];
          for (let i = 2; i < lines.length; i++) {
            const goodsInfo = lines[i].split(',');
            if (goodsInfo[0]) {
              const goods = {
                goods_id: goodsInfo[headers.indexOf('goods_id')],
                goods_name: goodsInfo[headers.indexOf('goods_name')],
                goods_desc: goodsInfo[headers.indexOf('goods_desc')] || '',
                goods_num: Number(goodsInfo[headers.indexOf('goods_num')])
              };
              const commodity = this.commodities.find(item => item.commodity_id === goods.goods_id);
              if (commodity && goods.goods_num > commodity.commodity_inventory) {
                this.$message.warning(`商品 ${goods.goods_name} 的数量不能超过库存 ${commodity.commodity_inventory}`);
                return;
              }
              this.order.order_goodslist.push(goods);
            }
          }
          this.$message.success('订单导入成功');
          this.calculateOrderPrice();
        } catch (error) {
          this.$message.error('订单导入失败：' + error.message);
          console.error(error);
        }
      };
      reader.onerror = () => {
        this.$message.error('文件读取失败');
      };
      reader.readAsText(file.raw);
    },
    // 下载导入模板
    downloadTemplate() {
      const headers = [
        'order_admin',
        'order_name',
        'order_id',
        'order_price',
        'order_status',
        'order_phone',
        'order_address',
        'order_province',
        'order_remark',
        'goods_id',
        'goods_name',
        'goods_desc',
        'goods_num'
      ];
      const csvContent = headers.join(',') + '\n' +
        '请填写订单管理员,请填写订单名称,请填写订单ID,请填写订单价格,请选择订单状态,请填写联系电话,请填写收货地址,请选择省份,请填写备注,请填写商品ID,请填写商品名称,请填写商品描述,请填写商品数量';
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      if (link.download !== undefined) {
        const url = URL.createObjectURL(blob);
        link.setAttribute('href', url);
        link.setAttribute('download', 'order_import_template.csv');
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    },
    // 计算订单价格
    calculateOrderPrice() {
      let totalPrice = 0;
      this.order.order_goodslist.forEach(goods => {
        const commodity = this.commodities.find(item => item.commodity_id === goods.goods_id);
        if (commodity) {
          totalPrice += commodity.commodity_price * goods.goods_num;
        }
      });
      this.order.order_price = totalPrice;
    },
    // 验证商品数量是否超过库存
    validateGoodsQuantity(goods) {
      const commodity = this.commodities.find(item => item.commodity_id === goods.goods_id);
      if (commodity && goods.goods_num > commodity.commodity_inventory) {
        this.$message.warning(`商品 ${goods.goods_name} 的数量不能超过库存 ${commodity.commodity_inventory}`);
        goods.goods_num = commodity.commodity_inventory;
      }
      this.calculateOrderPrice();
    }
  }
};
</script>

<style scoped>
.add-order {
  padding: 20px;
}
.el-form-item {
  margin-bottom: 20px;
}
.el-button {
  margin-top: 10px;
}
.custom-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
  font-family: Arial, sans-serif;
}
.custom-table thead {
  background-color: #f5f7fa;
}
.custom-table th,
.custom-table td {
  padding: 12px 15px;
  border: 1px solid #ebeef5;
  text-align: left;
}
.custom-table tr:nth-child(even) {
  background-color: #fafafa;
}
.custom-table tr:hover {
  background-color: #e6f7ff;
}
</style>